package com.hb.common.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hb.common.dto.Database;
import com.hb.common.dto.DbBackupTask;
import com.hb.common.service.DatabaseService;
import com.hb.common.service.DbBackupService;
import com.hb.common.service.DbBackupTaskService;
import com.hb.common.task.CronTaskHandler;
import com.hb.common.util.PropertiesUtil;
import com.hb.common.util.Result;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 备份任务
 */
@Service
public class DbBackupTaskServiceImpl implements DbBackupTaskService {

    private static final Logger log = LoggerFactory.getLogger(DbBackupTaskServiceImpl.class);

    @Resource
    private DbBackupService dbBackupService;
    @Resource
    private CronTaskHandler cronTaskHandler;
    @Resource
    private PropertiesUtil propertiesUtil;
    @Resource
    private DatabaseService databaseService;

    /**
     * 获取备份任务列表
     */
    @Override
    public Result<List<DbBackupTask>> selectList() {
        // 获取配置文件里的任务列表
        String backupTaskList = propertiesUtil.getValue("backupTaskList");
        List<DbBackupTask> backupTasks = BeanUtil.copyToList(JSONUtil.parseArray(backupTaskList), DbBackupTask.class);
        return Result.success(backupTasks);
    }

    /**
     * 保存或更新备份任务
     */
    @Override
    public Result<Boolean> insertOrUpdate(DbBackupTask backupTask) {
        Database database = databaseService.selectById(backupTask.getId()).getData();
        if (database == null) {
            return Result.fail("数据库不存在");
        }

        // 获取任务列表
        List<DbBackupTask> backupTasks = this.selectList().getData();
        // 根据id判断是否存在
        int index = backupTasks.indexOf(backupTask);
        if (index >= 0) {
            // 修改
            backupTasks.removeIf(x -> Objects.equals(x.getId(), backupTask.getId()));
            // 更新backupTaskList的值
            backupTasks.add(index, backupTask);
        } else {
            // 添加
            backupTasks.add(backupTask);
        }
        propertiesUtil.setValue("backupTaskList", JSONUtil.toJsonStr(backupTasks));

        // 添加定时任务
        this.addTask(backupTask);
        return Result.success();
    }

    /**
     * 根据id获取备份任务
     */
    @Override
    public Result<DbBackupTask> selectById(Integer id) {
        List<DbBackupTask> backupTaskList = this.selectList().getData();
        DbBackupTask backupTask = backupTaskList.stream().filter(x -> Objects.equals(x.getId(), id)).findFirst().orElse(null);
        return Result.success(backupTask);
    }

    /**
     * 删除备份任务
     */
    @Override
    public Result<Boolean> delete(List<Integer> ids) {
        for (Integer id : ids) {
            // 获取任务列表
            List<DbBackupTask> backupTasks = this.selectList().getData();
            backupTasks.removeIf(x -> Objects.equals(x.getId(), id));
            propertiesUtil.setValue("backupTaskList", JSONUtil.toJsonStr(backupTasks));
            // 移除定时任务
            this.removeTask(id);
        }
        return Result.success();
    }

    /**
     * 添加任务到定时器
     */
    @Override
    public void addTask(DbBackupTask task) {
        String cron = task.getCron();
        cronTaskHandler.addTask(() -> {
            try {
                dbBackupService.backup(task.getId());
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }, cron, task.getId());
    }

    /**
     * 移除定时器中的备份任务
     */
    @Override
    public void removeTask(Integer id) {
        cronTaskHandler.removeTask(id);
    }
}
